import tkinter as tk
from tkinter import messagebox, font
import sqlite3
import hashlib

def hash_password(password):
    """使用 SHA-256 哈希函数加密密码。"""
    sha_signature = hashlib.sha256(password.encode()).hexdigest()
    return sha_signature

class LoginWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("登录界面")
        self.root.geometry("600x400")

        self.font_large = font.Font(size=12)
        self.conn = sqlite3.connect('user.db')
        self.cursor = self.conn.cursor()

        self.label_username = tk.Label(self.root, text="用户名:", font=self.font_large)
        self.label_username.pack(pady=10)
        self.entry_username = tk.Entry(self.root, width=25, font=self.font_large)
        self.entry_username.pack(pady=10)

        self.label_password = tk.Label(self.root, text="密码:", font=self.font_large)
        self.label_password.pack(pady=10)
        self.entry_password = tk.Entry(self.root, width=25, show="*", font=self.font_large)
        self.entry_password.pack(pady=10)

        self.button_login = tk.Button(self.root, text="登录", command=self.login, font=self.font_large)
        self.button_login.pack(pady=20)

        self.button_register = tk.Button(self.root, text="注册", command=self.register, font=self.font_large)
        self.button_register.pack(pady=20)

        self.root.bind('<Return>', self.login)

        self.login_success = False
        self.username = None


    def login(self, event=None):
        username = self.entry_username.get()
        password = hash_password(self.entry_password.get())
        self.cursor.execute('SELECT * FROM users WHERE username=? AND password=?', (username, password))
        if self.cursor.fetchone():
            self.login_success = True
            self.username = username
            self.root.destroy()  # 关闭窗口
        else:
            messagebox.showerror("登录失败", "用户名或密码错误")
            self.root.destroy()  # 关闭窗口

    def register(self):
        username = self.entry_username.get()
        password = hash_password(self.entry_password.get())
        try:
            self.cursor.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, password))
            self.conn.commit()
            messagebox.showinfo("注册成功", "用户注册成功，请登录。")
        except sqlite3.IntegrityError:
            messagebox.showerror("注册失败", "该用户名已被注册，请尝试其他用户名。")

    def close(self):
        self.conn.commit()
        self.cursor.close()
        self.conn.close()
        self.root.destroy()

# 测试代码
if __name__ == "__main__":
    root = tk.Tk()
    app = LoginWindow(root)  
    root.protocol("WM_DELETE_WINDOW", app.close)
    root.mainloop()


# 可以在这里调用 run_login_window() 来测试你的界面
#run_login_window()
